<template>
  <div class="chart-container">
    <!-- 固定导航 -->
    <van-nav-bar fixed left-arrow @click-left="$router.back()" title="小思同学"></van-nav-bar>

    <!-- 聊天气泡区域 -->
    <div class="chart-list">
      <div v-for="(item,index) in list" :key="index">
        <div class="chart-item left" v-if="item.name !== 'me'">
          <van-image width="44" height="44" round src="https://img01.yzcdn.cn/vant/cat.jpeg" />
          <span class="chat-pao">{{item.msg}}</span>
        </div>
        <div class="chart-item right" v-else>
          <van-image width="44" height="44" round :src="$store.state.userPhoto" />
          <span class="chat-pao">{{item.msg}}</span>
        </div>
      </div>
    </div>

    <!-- 对话区域 -->
    <div class="reply-container van-hairline--top">
      <van-field v-model="word" placeholder="说点什么...">
        <template #button>
          <span style="font-size:12px;color:#999" @click="sendMsgFn">提交</span>
        </template>
      </van-field>
    </div>
  </div>

</template>

<script>
import { io } from 'socket.io-client'
import { getToken } from '@/utils/token.js'
export default {
  name: 'Chart',
  data() {
    return {
      word: '',
      list: [
        {
          name: 'xs',
          msg: 'hi!你好！我是小思！'
        }
      ],
      socket: null // 客户端和服务器端的soket对象
    }
  },
  created() {
    // 建立io链接
    this.socket = io('http://toutiao.itheima.net', {
      query: {
        token: getToken()
      },
      transports: ['websocket']
    })
    this.socket.on('connect', () => {
      // 与服务器成功建立连接时，发送一条提示（无实际沟通作用）
      this.list.push({
        name: 'me',
        msg: `你好！我是${this.$store.state.userName}`
      })
    })

    this.receiveMsgFn()
  },

  methods: {
    // 接收消息
    receiveMsgFn() {
      // 接收后端传来的消息
      this.socket.on('message', obj => {
        this.list.push({
          name: 'xs',
          msg: obj.msg
        })
        this.scrollView()
      })
    },

    // 消息自动滚动到可视范围
    scrollView() {
      this.$nextTick(() => {
        const theDiv = document.querySelector('.chart-list>div:last-child')
        theDiv.scrollIntoView({
          behavior: 'smooth'
        })
      })
    },

    // 发送消息按钮
    sendMsgFn() {
      if (this.word.trim().length !== 0) {
        // 向后端发送消息
        this.socket.emit('message', {
          msg: this.word,
          timestamp: new Date().getTime()
        })
        this.list.push({
          msg: this.word,
          name: 'me'
        })
        this.scrollView()
        this.word = ''
      }
    }
  },
  beforeDestroy() {
    this.socket.close()
    this.socket = null
  }
}
</script>

<style lang="less" scoped>
.chart-container {
  .chart-list {
    padding-top: 48px;
    padding-bottom: 50px;
    .chart-item {
      display: flex;
      padding: 16px 12px 0;
      .chat-pao {
        position: relative;
        font-size: 16px;
        border: 1px solid #c2d9ea;
        background-color: #e0effb;
        margin-left: 15px;
        min-width: 30px;
        max-width: 70%;
        min-height: 40px;
        line-height: 40px;
        word-break: break-all;
        padding: 0 10px;
        border-radius: 8px;
        &::after {
          content: '';
          position: absolute;
          top: 9px;
          display: block;
          border-left: 10px solid transparent;
          border-right: 10px solid #e0effb;
          border-top: 10px solid transparent;
          border-bottom: 10px solid transparent;
        }
      }
    }
    .left {
      .chat-pao {
        &::after {
          left: -18px;
        }
      }
    }
    .right {
      flex-direction: row-reverse;
      .chat-pao {
        margin-right: 15px;
        &::after {
          content: '';
          right: -18px;
          transform: rotate(-180deg);
        }
      }
    }
  }
  .reply-container {
    position: fixed;
    bottom: 0;
    background: #f5f5f5;
    z-index: 9999;
    .van-field {
      width: 375px;
    }
  }
}
</style>
